package org.example.todolist.controller;

import org.example.todolist.entity.TodoList;
import org.example.todolist.service.ListService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;

/**
 * 列表控制器
 */
@RestController
@RequestMapping("/api/lists")
public class ListController {

    @Autowired
    private ListService listService;

    /**
     * 获取用户的所有列表
     * @param userId 用户ID
     * @return 列表集合
     */
    @GetMapping
    public ResponseEntity<ArrayList<TodoList>> getAllLists(@RequestParam Integer userId) {
        ArrayList<TodoList> lists = listService.getListsByUserId(userId);
        return ResponseEntity.ok(lists);
    }

    /**
     * 获取特定列表
     * @param id 列表ID
     * @return 列表对象
     */
    @GetMapping("/{id}")
    public ResponseEntity<TodoList> getListById(@PathVariable Integer id) {
        TodoList list = listService.getListById(id);
        if (list != null) {
            return ResponseEntity.ok(list);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 创建新列表
     * @param list 列表对象
     * @return 创建的列表对象
     */
    @PostMapping
    public ResponseEntity<TodoList> createList(@RequestBody TodoList list) {
        TodoList createdList = listService.createList(list);
        if (createdList != null) {
            return ResponseEntity.status(HttpStatus.CREATED).body(createdList);
        } else {
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 更新列表
     * @param id 列表ID
     * @param list 列表对象
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public ResponseEntity<Void> updateList(@PathVariable Integer id, @RequestBody TodoList list) {
        list.setId(id);
        boolean result = listService.updateList(list);
        if (result) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 删除列表
     * @param id 列表ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteList(@PathVariable Integer id) {
        boolean result = listService.deleteList(id);
        if (result) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
